<?php
namespace App\Services;
use Exception,Log;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;
use App\Models\Linkslistsimages;

class BaidusbService
{
    // 获取百度AccessToken
    public static function getBaiduAccessToken()
    {
        $baidu_access_token = Redis::get("baidu_shibie_token");
        if (empty($baidu_access_token)) {
            $client_id = "3NwVTRvA3Gy7EWxtexAbNuVn";
            $client_secret = "i76AOKuyi36qx7UHdNGGynnbpRauo10v";
            $client = new Client;
            $response = $client->request('GET', 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='.$client_id.'&client_secret='.$client_secret);
            $body = $response->getBody()->getContents();
            $responsebody = json_decode($body);
            $baidu_access_token = $responsebody->access_token;
            Redis::setex("baidu_shibie_token", 2505600, $baidu_access_token);
        }
        return ["status"=>"success","msg"=>"获取成功！","baidu_access_token"=>$baidu_access_token];
    }

    public static function idcardOcr($imgurl,$side)
    {
        $accessToken = self::getBaiduAccessToken();
        $requestUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=".$accessToken["baidu_access_token"];
        $client = new Client;
        $response = $client->request('POST', $requestUrl, [
            'form_params' => [
                'url'=>$imgurl,
                'id_card_side'=>$side
            ]
        ]);
        $body = $response->getBody()->getContents();
        $responsebody = json_decode($body,true);
        return $responsebody;
    }

    public static function licenseOcr($imgurl)
    {
        $accessToken = self::getBaiduAccessToken();
        $requestUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=".$accessToken["baidu_access_token"];
        $client = new Client;
        $response = $client->request('POST', $requestUrl, [
            'form_params' => [
                'url'=>$imgurl,
            ]
        ]);
        $body = $response->getBody()->getContents();
        $responsebody = json_decode($body,true);
        return $responsebody;
    }
}
